/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package fix.it.source.fixit;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Asynchronous;
import javax.jms.*;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;


/**
 *
 * @author Aleksandra
 */
public class JMSSender {
    @PersistenceContext(unitName = "fix.it.source_FixIt_war_1.0-SNAPSHOTPU")
    private EntityManager em;

    private static String url = ActiveMQConnection.DEFAULT_BROKER_URL;
    private static String QueueName = "";
    
//    public void sendMessageToAuthority(Problem p) throws JMSException{
//        
//        QueueName = p.getAuthorityid().getName();
//        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
//        Connection connection = connectionFactory.createConnection();
//        connection.start();
//        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
//        Destination destination = session.createQueue(QueueName);
//        MessageProducer messageProducer = session.createProducer(destination);
//        String text = "Problem " + p.getProblemname() + " reported at " + p.getReportdateString() + " on the followind address:  " + p.getStreetid().getName() + " "+p.getStreetid().getNumber()+" " + p.getMunicipalityid().getName() + ".";
//        
//        TextMessage message = session.createTextMessage(text);
//        messageProducer.send(message);
//        System.out.println("Message:  '" + message.getText());
//        connection.close();
//    }
    
    @Asynchronous
    public void sendMessageToAuthority(Problem p){
    
        QueueName = p.getAuthorityid().getName();
        try{
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
        String text = "Problem " + p.getProblemname() + " reported at " + p.getReportdateString() + " on the followind address:  " + p.getStreetid().getName() + " "+p.getStreetid().getNumber()+" " + p.getMunicipalityid().getName() + ".";
        
        Connection connection = connectionFactory.createConnection();
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination destination = session.createQueue(QueueName);
        MessageProducer messageProducer = session.createProducer(destination);    
        TextMessage message = session.createTextMessage(text);
        messageProducer.send(message);
        System.out.println("Message to authority sent:  '" + message.getText());
        connection.close();
        }catch(JMSException ex){
        //Logger.getLogger(ReportProblemBean.class.getName()).log(Level.INFO, null, ex);
        }
    }
}
